package cn.rkylin.oms.common.utils;

import java.io.Serializable;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;

/**
 * OMS系统的Cookie操作工具 注意：不管是开发，还是测试、生产环境，都要使用域名，否则无效
 * 
 */
public class CookieUtil implements Serializable{
    private static final long serialVersionUID = 1500038311654892681L;
    /**
     * 日志工具log4j
     */
    private static Log log = LogFactory.getLog(CookieUtil.class);

    /**
     * 请求对象
     */
    private HttpServletRequest request;

    /**
     * 答复对象
     */
    private HttpServletResponse response;

    /**
     * 初始化request和response
     */
    private void init() {
        if (this.request == null) {
            this.request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        }
        if (this.response == null) {
            this.response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
        }
    }

    /**
     * 保存cookie 从CurrentUser 获取cookie信息（中文已经转码）
     * 
     * @param user
     *            当前登录进来的用户
     * @param rememberMe
     *            是否记住我
     * @param rememberDays
     *            记多少天，单位是天！
     */
    public void saveCookies(boolean rememberMe, int rememberDays) {
        init();

        CurrentUser user = WebContextFactory.getWebContext().getCurrentUser();

        List<Cookie> cookieList = new ArrayList<Cookie>();
        // 帐户
        cookieList.add(new Cookie("account", user.getAccount()));

        // 密码（加密）
        // cookieList.add(new Cookie("pasword", strEncode(user.getPassword())));

        // 密码（加密）
        cookieList.add(new Cookie("rememberMe", String.valueOf(rememberMe)));

        // cookie保存到客户端浏览器
        for (Cookie aCookie : cookieList) {
            if (rememberMe) {
                // 天转秒
                int sec = rememberDays * 24 * 60 * 60;
                aCookie.setMaxAge(sec); // 单位是秒

            } else { // 关闭浏览器即需要重新登录
                aCookie.setMaxAge(-1);
            }
            aCookie.setDomain(".ruixuesoft.com");
            aCookie.setPath("/");
            response.addCookie(aCookie);
        }
    }

    /**
     * 从cookie中获取当前用户的一些数据，用于“记住我”功能
     * 
     * @param request
     * @return
     */
    public CurrentUser getCurrentUserCookie() {
        init();
        CurrentUser cookieUser = new CurrentUser();
        Cookie[] cookieList = request.getCookies();
        if (cookieList != null) {
            for (Cookie aCookie : cookieList) {
                if (aCookie.getName().equalsIgnoreCase("account")) {
                    cookieUser.setAccount(aCookie.getValue());
                }
//                else if (aCookie.getName().equalsIgnoreCase("pasword")) {
//                    cookieUser.setPassword(strDecode(aCookie.getValue()));
//                }
            }
        }
        return cookieUser;
    }
    
    /**
     * 按名称获取cookie对象
     * @param cookieName
     * @return
     */
    public Cookie getCookie(String cookieName) {
        init();
        Cookie returnCookie = null;
        Cookie[] cookieList = request.getCookies();
        if (cookieList != null) {
            for (Cookie aCookie : cookieList) {
                if (aCookie.getName().equalsIgnoreCase(cookieName)) {
                    returnCookie = aCookie;
                }
            }
        }
        return returnCookie;
    }

    /**
     * 删除浏览器所有本站cookie
     * 
     * @param request
     * @return
     */
    public void removeCookies() {
        init();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie aCookie = cookies[i];
                if (aCookie.getName().equalsIgnoreCase("account")// || aCookie.getName().equalsIgnoreCase("password")
                        || aCookie.getName().equalsIgnoreCase("rememberMe")) {
                    aCookie.setMaxAge(0); // 0表示删除cookie
                    aCookie.setDomain(".ruixuesoft.com");
                    aCookie.setPath("/");
                    response.addCookie(aCookie);
                }
            }
        }
    }

    /**
     * 接口传递中文参数转码
     * 
     * @param str
     * @return
     */
    private String strEncode(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        String resultStr = null;
        try {
            // TODO 加密
            resultStr = URLEncoder.encode(str, "utf-8");
        } catch (Exception e) {
            log.error("中文Encoder转码异常！", e);
        }
        return resultStr;
    }

    /**
     * 接口传递中文参数解码
     * 
     * @param str
     * @return
     */
    private String strDecode(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        String resultStr = null;
        try {
            // TODO 解密
            resultStr = URLDecoder.decode(str, "UTF-8");
        } catch (Exception e) {
            log.error("中文Encoder解码异常！", e);
        }
        return resultStr;
    }

    /**
     * 删除cookie
     * @param cookieName
     */
    public void removeCookie(String cookieName) {
        init();
        Cookie delCookie = getCookie(cookieName);
        delCookie.setMaxAge(0);
        response.addCookie(delCookie);
    }

    /**
     * 创建一个新的cookie
     * @param theName cookie的名字
     * @param theValue cookie的值
     * @param rememberMe 是否记住我
     * @param rememberDays 记住天数（单位天）
     */
    public Cookie addCookie(String theName, String theValue, boolean rememberMe, int rememberDays) {
        if (StringUtils.isEmpty(theName) || StringUtils.isEmpty(theValue)) {
            return null;
        }
        init();
        Cookie newCookie = new Cookie(theName.trim(), theValue.trim());
        if (rememberMe) {
            // 天转秒
            int sec = rememberDays * 24 * 60 * 60;
            newCookie.setMaxAge(sec); // 单位是秒
        } else { // 关闭浏览器即需要重新登录
            newCookie.setMaxAge(-1);
        }
        newCookie.setDomain(".ruixuesoft.com");
        newCookie.setPath("/");
        response.addCookie(newCookie);
        
        return newCookie;
    }
}
